package applications.callcost;

import java.io.InputStream;
import java.text.DecimalFormat;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import applications.callcost.listeners.ArrowTouchListener;
import applications.callcost.listeners.DismissListener;

public class CallCostMain extends Activity {
	public static final int SCATTO_DIALOG=0,
							MINUTE_COST_DIALOG=1,
							ADDITIONAL_COST_DIALOG=2,
							ERROR_DIALOG=3,
							ADDITIONAL_TIME_DIALOG=4,
							EMPY_ERROR_DIALOG=5,
							INSTRUCTIONS_DIALOG=6,
							SMS_DIALOG=7,
							MMS_DIALOG=8,
							CREDIT_DIALOG=9;
	
	
	public static SharedPreferences settings;
	SharedPreferences.Editor editor;
	final String PREFS_NAME = "prefs";
	
	public static final String SCATTO="sc",
							   MINUTE_COST="sm",
							   ADDITIONAL_COST="ac",
							   ADDITIONAL_TIME="ad",
							   ADDITIONAL_ON="ao",
							   SMS_COST="rm",
							   MMS_COST="mm",
							   CREDIT_LEFT="cl";
	
	final int MENU_NOTIFICATION=0, MENU_DIALOG=1, MENU_ISTR=2;
	
	Resources res;
	
	CheckBox checkbox, notChk, diaChk;
	
	private OnClickListener buttonListener = new OnClickListener() {
	    public void onClick(View v) {
	    	switch(v.getId()){
        	  
	    	case R.id.scattoBtn:
    			showDialog(SCATTO_DIALOG);
    			break;
    			
	    	case R.id.additionalBtn:
    			showDialog(ADDITIONAL_COST_DIALOG);
    			break;
    			
	    	case R.id.costoMinBtn:
    			showDialog(MINUTE_COST_DIALOG);
    			break;
    			
	    	case R.id.additionalTimeBtn:
	    		showDialog(ADDITIONAL_TIME_DIALOG);
	    		break;
	    		
	    	case R.id.smsBtn:
	    		showDialog(SMS_DIALOG);
	    		break;
	    		
	    	case R.id.mmsBtn:
	    		showDialog(MMS_DIALOG);
	    		break;
	    		
	    	case R.id.creditoBtn:
	    		showDialog(CREDIT_DIALOG);
	    		break;
	    		
	    	case R.id.okInstr:
	    		dismissDialog(INSTRUCTIONS_DIALOG);
	    		break;
	    		
	    	case R.id.additionalTitle:
	    		checkbox.setChecked(!checkbox.isChecked());
	    		break;
	        	  
	    	}
	   }
	};
	
	public SharedPreferences.Editor getEditor(){
		return editor;
	}
	
	public SharedPreferences getPreferences(){
		return settings;
	}
		
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //TODO decommentare e implementare il listener sms mandati
        //findViewById(R.id.mmsBtn).setVisibility(View.GONE);
        //findViewById(R.id.mmsText).setVisibility(View.GONE);
        
        res = getResources();
        
        //carico le preferenze
		settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
	    editor   = settings.edit();
	    
	    checkbox=(CheckBox)findViewById(R.id.additionalCheck);
	    
	    checkbox.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener(){

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					
				editor.putBoolean(ADDITIONAL_ON, isChecked);
				editor.commit();

				if(isChecked)
					findViewById(R.id.innerTable).setVisibility(View.VISIBLE);
				else 
					findViewById(R.id.innerTable).setVisibility(View.GONE);
			}
	    	
	    });
	    
	    notChk=(CheckBox)findViewById(R.id.notificationCheck);
	    
	    notChk.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener(){

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					
				editor.putBoolean("notification", isChecked);
	        	editor.commit();

			}
	    	
	    });
	    
	    diaChk=(CheckBox)findViewById(R.id.toastCheck);
	    
	    diaChk.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener(){

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					
				editor.putBoolean("dialog", isChecked);
	        	editor.commit();

			}
	    	
	    });
	    
	    checkbox.setChecked(settings.getBoolean(ADDITIONAL_ON, false));
	    
	    notChk.setChecked(settings.getBoolean("notification", true));
	    
	    diaChk.setChecked(settings.getBoolean("dialog", true));
	    
	    if(checkbox.isChecked())
			findViewById(R.id.innerTable).setVisibility(View.VISIBLE);
		else 
			findViewById(R.id.innerTable).setVisibility(View.GONE);
	    
	    findViewById(R.id.additionalTitle).setOnClickListener(buttonListener);
        
	    findViewById(R.id.scattoBtn).setOnClickListener(buttonListener);
        ((TextView)findViewById(R.id.scattoText)).setText(settings.getInt(SCATTO, 0)+" cents");
        
        findViewById(R.id.additionalBtn).setOnClickListener(buttonListener);
        ((TextView)findViewById(R.id.additionalText)).setText(settings.getInt(ADDITIONAL_COST, 0)+" cents");
        
        findViewById(R.id.costoMinBtn).setOnClickListener(buttonListener);
        ((TextView)findViewById(R.id.costoMinText)).setText(settings.getInt(MINUTE_COST, 0)+" cents");
        
        findViewById(R.id.additionalTimeBtn).setOnClickListener(buttonListener);
        ((TextView)findViewById(R.id.additionalTimeText)).setText(settings.getInt(ADDITIONAL_TIME, 0)+" "+res.getString(R.string.seconds));
        
        findViewById(R.id.smsBtn).setOnClickListener(buttonListener);
        ((TextView)findViewById(R.id.smsText)).setText(settings.getInt(SMS_COST, 0)+" cents");
        
        findViewById(R.id.mmsBtn).setOnClickListener(buttonListener);
        ((TextView)findViewById(R.id.mmsText)).setText(settings.getInt(MMS_COST, 0)+" cents");
        
        findViewById(R.id.creditoBtn).setOnClickListener(buttonListener);
        ((TextView)findViewById(R.id.creditoText)).setText((new DecimalFormat("0.##").format((double)settings.getFloat(CREDIT_LEFT, 0)))+"");
        try {
            Intent svc = new Intent(this, CallListenerService.class);
            startService(svc);
        }
        catch (Exception e) {
            
        }
    }
    
    public void onWindowFocusChanged (boolean hasFocus){
    	super.onWindowFocusChanged(hasFocus);
    	
    	if(!hasFocus)
    		return;
    	
    	((TextView)findViewById(R.id.creditoText)).setText((new DecimalFormat("0.##").format((double)settings.getFloat(CREDIT_LEFT, 0)))+"");
    	((TextView)findViewById(R.id.scattoText)).setText(settings.getInt(SCATTO, 0)+" cents");
        ((TextView)findViewById(R.id.additionalText)).setText(settings.getInt(ADDITIONAL_COST, 0)+" cents");
        ((TextView)findViewById(R.id.costoMinText)).setText(settings.getInt(MINUTE_COST, 0)+" cents");
        ((TextView)findViewById(R.id.smsText)).setText(settings.getInt(SMS_COST, 0)+" cents");
        ((TextView)findViewById(R.id.mmsText)).setText(settings.getInt(MMS_COST, 0)+" cents");
        ((TextView)findViewById(R.id.additionalTimeText)).setText(settings.getInt(ADDITIONAL_TIME, 0)+" "+res.getString(R.string.seconds));
    }
    
    
    protected Dialog onCreateDialog(int id) {
    	AlertDialog.Builder builder;
    	
    	Dialog dialog;
        dialog = new Dialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.inputdialog);
        
        EditText ed=(EditText)dialog.findViewById(R.id.inputText);
        
        ArrowTouchListener at=new ArrowTouchListener(ed);		
		dialog.findViewById(R.id.decrement).setOnTouchListener(at);
		dialog.findViewById(R.id.increment).setOnTouchListener(at);
        
        switch(id){
        
        case CREDIT_DIALOG:
        	dialog.findViewById(R.id.decrement).setVisibility(View.GONE);
        	dialog.findViewById(R.id.increment).setVisibility(View.GONE);
        	dialog.findViewById(R.id.ok).setOnClickListener(new DismissListener(this, CREDIT_DIALOG, ed));
    		((TextView)dialog.findViewById(R.id.title)).setText(res.getString(R.string.credito));
    		ed.setText(settings.getFloat(CREDIT_LEFT, 0)+"");
        	break;
        	
        case SCATTO_DIALOG:
    		dialog.findViewById(R.id.ok).setOnClickListener(new DismissListener(this, SCATTO_DIALOG, ed));
    		((TextView)dialog.findViewById(R.id.title)).setText(res.getString(R.string.scatto));
    		ed.setText(settings.getInt(SCATTO, 0)+"");
    		break;
    		
        case MINUTE_COST_DIALOG:
    		dialog.findViewById(R.id.ok).setOnClickListener(new DismissListener(this, MINUTE_COST_DIALOG, ed));
    		((TextView)dialog.findViewById(R.id.title)).setText(res.getString(R.string.minuteCharge));
    		ed.setText(settings.getInt(MINUTE_COST, 0)+"");
    		break;
    		
        case SMS_DIALOG:
    		dialog.findViewById(R.id.ok).setOnClickListener(new DismissListener(this, SMS_DIALOG, ed));
    		((TextView)dialog.findViewById(R.id.title)).setText(res.getString(R.string.smsString));
    		ed.setText(settings.getInt(SMS_COST, 0)+"");
    		break;
    		
        case MMS_DIALOG:
    		dialog.findViewById(R.id.ok).setOnClickListener(new DismissListener(this, MMS_DIALOG, ed));
    		((TextView)dialog.findViewById(R.id.title)).setText(res.getString(R.string.mmsString));
    		ed.setText(settings.getInt(MMS_COST, 0)+"");
    		break;
    		
        case ADDITIONAL_COST_DIALOG:
    		dialog.findViewById(R.id.ok).setOnClickListener(new DismissListener(this, ADDITIONAL_COST_DIALOG, ed));
    		((TextView)dialog.findViewById(R.id.title)).setText(res.getString(R.string.addcost));
    		ed.setText(settings.getInt(ADDITIONAL_COST, 0)+"");
    		break;
    		
        case ADDITIONAL_TIME_DIALOG:
        	dialog.findViewById(R.id.ok).setOnClickListener(new DismissListener(this, ADDITIONAL_TIME_DIALOG, ed));
    		((TextView)dialog.findViewById(R.id.title)).setText(res.getString(R.string.addtime));
    		ed.setText(settings.getInt(ADDITIONAL_TIME, 0)+"");
        	break;
    		
        case ERROR_DIALOG:
        	builder = new AlertDialog.Builder(this);
        	builder.setMessage(res.getString(R.string.numbersonly))
  	       .setCancelable(false)
  	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
  	           public void onClick(DialogInterface dialog, int id) {
  	                
  	           }
  	       });
            dialog = builder.create();
        	break;
        	
        case EMPY_ERROR_DIALOG:
        	builder = new AlertDialog.Builder(this);
        	builder.setMessage(res.getString(R.string.emptywarning))
  	       .setCancelable(false)
  	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
  	           public void onClick(DialogInterface dialog, int id) {
  	                
  	           }
  	       });
            dialog = builder.create();
        	break;
        	
        case INSTRUCTIONS_DIALOG:
        	dialog = new Dialog(this);
        	dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        	dialog.setContentView(R.layout.instrdialog);

        	try {
        		InputStream instrStr=res.openRawResource(R.raw.instructionsfile);
            	byte [] text=new byte[640];
				instrStr.read(text);
				((TextView)dialog.findViewById(R.id.instrText)).setText(new String(text));
			} catch (Exception e) {
				((TextView)dialog.findViewById(R.id.instrText)).setText("Error loading instructions");
			}
        	
            dialog.findViewById(R.id.okInstr).setOnClickListener(buttonListener);
            break;
        }
        
        return dialog;
    }
    
    //chiamata quando viene aperto per la prima volta il menu
    
    public boolean onCreateOptionsMenu (Menu menu){

    	 menu.add(Menu.NONE, MENU_ISTR, 0, res.getString(R.string.instr));
    	
    	return true;
    }
    

    
    //chiamata quando viene seletionato un pulsante nel menu
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        	
        case MENU_ISTR:
        	showDialog(INSTRUCTIONS_DIALOG);
        	break;
        		
        }
        return true;
    }
}